package com.lp.common.component;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.UUID;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-03-11 21:13:09
 */
public class CommonThreadPool {

    private CommonThreadPool() {}

    public static final String APP_NUMBER = UUID.randomUUID().toString().split("-")[0];

    public static final int MAX_THREAD_COUNT = 10;

    /**
     * The constant EXECUTOR.
     */
    public static final ThreadPoolTaskExecutor EXECUTOR;

    static {
        EXECUTOR = new ThreadPoolTaskExecutor();
        //配置核心线程数
        EXECUTOR.setCorePoolSize(MAX_THREAD_COUNT);
        //配置最大线程数
        EXECUTOR.setMaxPoolSize(100);
        //配置队列大小
        EXECUTOR.setQueueCapacity(99999);
        //配置线程池中的线程的名称前缀
        EXECUTOR.setThreadNamePrefix("async-common-" + APP_NUMBER + "-");

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        EXECUTOR.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        EXECUTOR.initialize();
    }
}

